import '../sass/login.scss'

const form = document.querySelector('form')
const nameInp = document.querySelector('.user')
const pwdInp = document.querySelector('.pwd')
const errBox = document.querySelector('.error')

const  bannerLogin = document.querySelector('.banner_box_rig > .top > .login >.rig1 > .top > .xuanran ')

form.addEventListener('submit', e => {
  e.preventDefault()

  // 采集信息
  const name = nameInp.value
  const pwd = pwdInp.value

  // 验证
  if (!name || !pwd) return alert('请完整填写表单 !')

  // 发送请求
  const xhr = new XMLHttpRequest()

  xhr.open('POST', 'http://localhost:8888/users/login')

  xhr.onload = function () {
    const res = JSON.parse(xhr.responseText)
    if (res.code === 0) {
      errBox.style.display = 'block'
      return
    }

    alert('登录成功')

    window.localStorage.setItem('id', res.user.id)
    window.localStorage.setItem('token', res.token)
    window.location.href = 'index.html'
    bannerLogin.innerText = res.user.nickname
  }

  xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')

  xhr.send(`username=${ name }&password=${ pwd }`)
})
